#include "mainweather.h"
#include "ui_weather.h"
#include "weathertool.h"
#include <QMessageBox>
#include <QFile>
#include <QPen>
#include <QPainter>
#include <QBrush>
#include <QFont>
MainWeather::MainWeather(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Weather)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setFixedSize(width(),height());
    //初始化城市名map
    WeatherTool::initWCityMap();


    //初始化控件容器
    dateLbList<<ui->date0Lb<<ui->date1Lb<<ui->date2Lb<<ui->date3Lb<<ui->date4Lb<<ui->date5Lb;
    qualityLbList<<ui->quality0Lb<<ui->quality1Lb<<ui->quality2Lb<<ui->quality3Lb<<ui->quality4Lb<<ui->quality5Lb;
    typeLbList<<ui->type0Lb<<ui->type1Lb<<ui->type2Lb<<ui->type3Lb<<ui->type4Lb<<ui->type5Lb;
    highLbList<<ui->high0Lb<<ui->high1Lb<<ui->high2Lb<<ui->high3Lb<<ui->high4Lb<<ui->high5Lb;
    lowLbList<<ui->low0Lb<<ui->low1Lb<<ui->low2Lb<<ui->low3Lb<<ui->low4Lb<<ui->low5Lb;
    typeIcoLbList<<ui->typeIco0Lb<<ui->typeIco1Lb<<ui->typeIco2Lb<<ui->typeIco3Lb<<ui->typeIco4Lb<<ui->typeIco5Lb;

    //创建退出菜单项
    exitMenu=new QMenu();
    exitAction=new QAction("退出");
    exitAction->setIcon(QIcon(":/weatherIco/close.ico"));
    exitMenu->addAction(exitAction);
    connect(exitAction,QAction::triggered,this,[=](){
        qApp->exit(0);
    });

    networkAccessManager=new QNetworkAccessManager(this);
    connect(networkAccessManager,&QNetworkAccessManager::finished,this,&replyHandle);

    requestWeather("101010100");


//    for(int i=0;i<6;i++)
//    {
//        QString s=wDays[i].high;
//        qDebug()<<"测试用例："<<s;
//    }



}



MainWeather::~MainWeather()
{
    delete ui;
}

void MainWeather::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos()-offset);
}

void MainWeather::mousePressEvent(QMouseEvent *event)
{
    offset=event->globalPos()-this->pos();
}

void MainWeather::replyHandle(QNetworkReply *reply)
{
    qDebug()<<"请求成功";
    int statusCode=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
//    qDebug()<<"statuscode:"<<statusCode;
    if(reply->error()!=QNetworkReply::NoError||statusCode!=200)
    {
        qDebug()<<"error:"<<reply->errorString().toLatin1().data();
        return;
    }
    //    qDebug()<<"statusCode  "<<statusCode;
    //    qDebug()<<reply->readAll();
    QByteArray byteArray=reply->readAll();
    parseJson(byteArray);
    updateUi();

    //对温度曲线label安装事件过滤器
    qDebug()<<"开始准备安装事件过滤器";
    ui->curveLb->installEventFilter(this);
    //更新温度曲线绘制事件
    ui->curveLb->update();

    //结束操作前
    reply->deleteLater();

}

void MainWeather::requestWeather(QString cityCode)
{
    QUrl cityUrl=QUrl("http://t.weather.itboy.net/api/weather/city/"+cityCode);
    networkAccessManager->get(QNetworkRequest(cityUrl));
}

void MainWeather::contextMenuEvent(QContextMenuEvent *event)
{
    //在光标所在位置弹出相应菜单项
    exitMenu->exec(QCursor::pos());
    event->accept();
}

void MainWeather::parseJson(QByteArray &byteArray)
{

    QJsonParseError error;
    QJsonDocument doc=QJsonDocument::fromJson(byteArray,&error);
    qDebug()<<"doc:"<<doc.isNull();
    if(error.error==QJsonParseError::IllegalValue)
    {
        qDebug()<<"error错误";
        //        qDebug()<<error.errorString();
        return;
    }
    QJsonObject obj=doc.object();
    qDebug()<<"message:"<<obj.value("message").toString();
    //wToday对象
    QString todayDate;
    QString jsonDate=obj.value("date").toString();
    todayDate=jsonDate.left(4)+"-"+jsonDate.mid(4,2)+"-"+jsonDate.right(2);
    qDebug()<<"todayDate:"<<todayDate;
    wToday.date=todayDate;

    wToday.quality=obj.value("data").toObject().value("quality").toString();
    wToday.wendu=obj.value("data").toObject().value("wendu").toString();
    wToday.city=obj.value("cityInfo").toObject().value("city").toString();
    wToday.type=obj.value("data").toObject().value("forecast").toArray().at(0).toObject().value("type").toString();
    wToday.notice=obj.value("data").toObject().value("forecast").toArray().at(0).toObject().value("notice").toString();
    wToday.shidu=obj.value("data").toObject().value("shidu").toString();
    wToday.pm25=obj.value("data").toObject().value("pm25").toInt();
    wToday.fx=obj.value("data").toObject().value("forecast").toArray().at(0).toObject().value("fx").toString();
    wToday.fl=obj.value("data").toObject().value("forecast").toArray().at(0).toObject().value("fl").toString();
    wToday.ganmao=obj.value("data").toObject().value("ganmao").toString();

    //wDays对象数组
    wDays[0].date=obj.value("data").toObject().value("yesterday").toObject().value("ymd").toString();
    wDays[0].aqi=obj.value("data").toObject().value("yesterday").toObject().value("aqi").toInt();
    qDebug()<<"质量："<<wDays[0].aqi;
    wDays[0].type=obj.value("data").toObject().value("yesterday").toObject().value("type").toString();
    wDays[0].high=obj.value("data").toObject().value("yesterday").toObject().value("high").toString();
    wDays[0].low=obj.value("data").toObject().value("yesterday").toObject().value("low").toString();

    for(int i=1;i<=5;i++)
    {
        wDays[i].date=obj.value("data").toObject().value("forecast").toArray().at(i-1).toObject().value("ymd").toString();
        wDays[i].aqi=obj.value("data").toObject().value("forecast").toArray().at(i-1).toObject().value("aqi").toInt();
        wDays[i].type=obj.value("data").toObject().value("forecast").toArray().at(i-1).toObject().value("type").toString();
        wDays[i].high=obj.value("data").toObject().value("forecast").toArray().at(i-1).toObject().value("high").toString();
        wDays[i].low=obj.value("data").toObject().value("forecast").toArray().at(i-1).toObject().value("low").toString();
    }
}

void MainWeather::updateUi()
{
    ui->dateLb->setText(wToday.date);
    ui->qualityLb->setText(wToday.quality);
    ui->temLb->setText(wToday.wendu+"°");
    ui->cityLb->setText(wToday.city);
    ui->noticeLb->setText(wToday.notice);
    ui->shiduLb->setText(wToday.shidu);
    ui->pm25Lb->setText(QString::number(wToday.pm25));
    ui->fxLb->setText(wToday.fx);
    ui->flLb->setText(wToday.fl);
    ui->ganmaoBrowser->setText(wToday.ganmao);
    ui->typeIcoLb->setStyleSheet( tr("border-image: url(:/day/day/%1.png); background-color: argb(60, 60, 60, 0);").arg(ui->typeLb->text()));

    for(int i=0;i<6;i++)
    {
        dateLbList[i]->setText(wDays[i].date.split("-").at(1)+"/"+wDays[i].date.split("-").at(2));
        //        qualityLbList[i]->setText(wDays[i].aqi);
        //空气质量指数分类
        int aqi=wDays[i].aqi;
        if(aqi<0)
        {

        }
        else if(aqi<=50)
        {
            qualityLbList[i]->setText("优");
            qualityLbList[i]->setStyleSheet("color: rgb(0, 255, 0);");
        }
        else if(aqi<=100)
        {
            qualityLbList[i]->setText("良");
            qualityLbList[i]->setStyleSheet("color: rgb(255, 255, 0);");
        }
        else if(aqi<=150)
        {
            qualityLbList[i]->setText("轻度");
            qualityLbList[i]->setStyleSheet("color: rgb(255, 170, 0);");
        }
        else if(aqi<=200)
        {
            qualityLbList[i]->setText("重度");
            qualityLbList[i]->setStyleSheet("color: rgb(255, 0, 0);");
        }
        else
        {
            qualityLbList[i]->setText("严重");
            qualityLbList[i]->setStyleSheet("color: rgb(170, 0, 0);");
        }

        typeLbList[i]->setText(wDays[i].type);
        highLbList[i]->setText(wDays[i].high.right(3));
        lowLbList[i]->setText(wDays[i].low.right(3));
        //        typeIcoLbList[i]->setStyleSheet( tr("border-image: url(:/day/day/%1.png); background-color: argb(60, 60, 60, 0);").arg(wDays[i].type));
        typeIcoLbList[i]->setPixmap(QPixmap(QString(":/day/day/%1.png").arg(wDays[i].type)));
    }
}

bool MainWeather::eventFilter(QObject *watched, QEvent *event)
{

    if(watched==ui->curveLb&&event->type()==QEvent::Paint)
    {
        qDebug()<<"调用paintTempCurve";
        paintTempCurve();
    }
    return QWidget::eventFilter(watched,event);
}

void MainWeather::paintTempCurve()
{
    QPainter painter(ui->curveLb);
    painter.setRenderHint(QPainter::Antialiasing, true); // 启用抗锯齿
    //初始化温度节点盒子
    for(int i=0;i<6;i++)
    {
        //绘制最高温曲线
        xPointArray[i]=highLbList[i]->x()+highLbList[i]->width()/2;

    }
    //最高温节点y值数据
    int sumHigh=0;
    for(int i=0;i<6;i++)
    {
        QString s=wDays[i].high.split(" ").at(1);
        int high=s.left(s.size()-1).toInt();
        sumHigh+=high;
        highYArray[i]=high;
    }
    int averHigh=sumHigh/6;

    //最低温节点y值数据
    int sumLow=0;
    for(int i=0;i<6;i++)
    {
        QString s=wDays[i].low.split(" ").at(1);
        int low=s.left(s.size()-1).toInt();
        sumLow+=low;
        lowYArray[i]=low;
    }
    int averLow=sumLow/6;

    for(int i=0;i<6;i++)
    {
        yHighPointArray[i]=ui->curveLb->height()/3+(averHigh-highYArray[i])*3;  //3是偏移值，以便在温度曲线上更好区分位置
        yLowPointArray[i]=ui->curveLb->height()/3*2+(averLow-lowYArray[i])*3;
//        qDebug()<<"y坐标值："<<yHighPointArray[i];
    }
    //最高温部分绘制
    QPen pen;
    pen.setWidth(1);
    pen.setColor(QColor(255,177,0));
    painter.setPen(pen);

    QFont font("Arial", 8); // 第二个参数是字体的点大小，可以根据需要调整
    // 设置字体
    painter.setFont(font);

    QBrush brush(QColor(255,177,0));
    painter.setBrush(brush);
//    painter.setBrush(QColor(255,177,0));
    //绘制最高温曲线节点
    for(int i=0;i<6;i++)
    {
        painter.drawEllipse(QPoint(xPointArray[i],yHighPointArray[i]),3,3);
        painter.drawEllipse(QPoint(xPointArray[i],yLowPointArray[i]),3,3);
        //绘制最高温文本框
        painter.drawText(QPoint(xPointArray[i]-10,yHighPointArray[i]-10),wDays[i].high.right(3));
        painter.drawText(QPoint(xPointArray[i]-10,yLowPointArray[i]+18),wDays[i].low.right(3));
    }
    for(int i=0;i<5;i++)
    {
        if(i==0)
        {
            pen.setStyle(Qt::DotLine);
            painter.setPen(pen);
        }
        else
        {
            pen.setStyle(Qt::SolidLine);
            painter.setPen(pen);
        }
        painter.drawLine(QPoint(xPointArray[i],yHighPointArray[i]),QPoint(xPointArray[i+1],yHighPointArray[i+1]));
    }

    //最低温部分绘制
    pen.setColor(QColor(0,255,255));
    painter.setPen(pen);
    painter.setBrush(QColor(0,255,255));
    for(int i=0;i<6;i++)
    {
        painter.drawEllipse(QPoint(xPointArray[i],yLowPointArray[i]),3,3);
        painter.drawText(QPoint(xPointArray[i]-10,yLowPointArray[i]+18),wDays[i].low.right(3));
    }
    for(int i=0;i<5;i++)
    {
        if(i==0)
        {
            pen.setStyle(Qt::DotLine);
            painter.setPen(pen);
        }
        else
        {
            pen.setStyle(Qt::SolidLine);
            painter.setPen(pen);
        }
        painter.drawLine(QPoint(xPointArray[i],yLowPointArray[i]),QPoint(xPointArray[i+1],yLowPointArray[i+1]));
    }
}

void MainWeather::initIconMap()
{
    //    typeMap.insert("暴雪",":/day/day/暴雪.png");

}

void MainWeather::on_searchBt_clicked()
{
    QString cityCode=WeatherTool::getCityCode(ui->cityLineEdit->text());
    if(cityCode.size()==0)
    {
        QMessageBox::warning(this,"城市天气查询","你输入的城市不存在");
        return;
    }
    this->requestWeather(cityCode);

}
